package xyz.icxl.android.architecture.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.ToastUtils
import xyz.icxl.android.architecture.dialog.LoadingDialog
import xyz.icxl.android.architecture.observer.PageLoadingStatusObserver
import xyz.icxl.android.architecture.observer.PageSnackBarStatusObserver

/**
 * 文件描述：基础的Fragment
 *
 * 文件创建人：ChenXinLei
 *
 * 文件创建人联系方式：502616659(QQ)
 *
 * 创建时间：2020 年 05月 25 日
 *
 * 文件版本：v1.0
 *
 * 版本描述：创建文件
 */
abstract class BaseFragment<DB : ViewDataBinding> : Fragment() {
    //是否是第一次渲染
    protected var isFirstRendering = true
    protected lateinit var dataBinding: DB
    protected val pageLoadingDialogStatus by lazy {
        PageLoadingStatusObserver(childFragmentManager)
    }
    protected val pageSnackbarStatusObserver by lazy {
        PageSnackBarStatusObserver(dataBinding.root)
    }
    abstract val layoutId: Int
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (!this::dataBinding.isInitialized) {//没有初始化过
            dataBinding = DataBindingUtil.inflate(
                inflater, layoutId, container, false
            )
            dataBinding.lifecycleOwner = this
        }
        return dataBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        if (isFirstRendering) {
            initData()
        }
        isFirstRendering = false
    }

    abstract fun initView()

    abstract fun initData()

    override fun onDestroyView() {
        if (pageLoadingDialogStatus.loadingDialog?.isShowing == true)
            pageLoadingDialogStatus.loadingDialog?.dismiss()
        pageSnackbarStatusObserver.dismiss()
        if (loadingDialog?.isShowing == true)
            loadingDialog?.dismiss()
        super.onDestroyView()
    }

    private var loadingDialog: LoadingDialog? = null
    open fun showLoadingDialog(msg: String = "加载中...") {
        if (null == loadingDialog) {
            loadingDialog = LoadingDialog(msg);
        }
        loadingDialog?.show(childFragmentManager)
    }

    open fun loadingFail(msg: String? = null) {
        loadingDialog?.dismiss()
        if (!msg.isNullOrEmpty())
            ToastUtils.showShort(msg)
    }

    open fun loadingSuccess(msg: String? = null) {
        loadingDialog?.dismiss()
        if (!msg.isNullOrEmpty())
            ToastUtils.showShort(msg)
    }

    open fun dismissLoadingDialog() {
        loadingDialog?.dismiss()
    }
}